package weight;

import android.app.Activity;
import android.content.Context;
import android.support.v4.view.ViewCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.common.R;
import com.google.android.flexbox.FlexboxLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import adapter.HistoryAdapter;
import constant.EventConstant;
import utils.ScreenUtils;
import utils.SizeUtils;
import utils.StringUtils;


/**
 * Created by yetwish on 2015-05-11
 */

public class SearchView extends LinearLayout implements View.OnClickListener{

    /**
     * 输入框
     */
    private EditText etInput;

    private View statusBar;

    /**
     * 删除键
     */
    private ImageView ivDelete;

    /**
     * 返回按钮
     */
    private ImageView btnBack;

    /**
     * 上下文对象
     */
    private Context mContext;

    /**
     * 弹出列表
     */
    private MyListView lvTips;

    /**
     * 提示adapter （推荐adapter）
     */
    private HistoryAdapter mHistoryAdapter;

    /**
     * 自动补全adapter 只显示名字
     */
    private ArrayAdapter<String> mAutoCompleteAdapter;

    /**
     * 搜索回调接口
     */
    private SearchViewListener mListener;

    /**
     * 取消点击
     */
    private OnClickListener backmListener;

    public void setBackmListener(OnClickListener backmListener) {
        this.backmListener = backmListener;
    }
    /**
     * 搜索标签 流式布局
     */
//    public AutoLineFeedLayout mFBLayout;
    public FlexboxLayout mFBLayout;
    private RelativeLayout mRlTabStr;

    /**
     * 设置搜索回调接口
     *
     * @param listener 监听者
     */
    public void setSearchViewListener(SearchViewListener listener) {
        mListener = listener;
    }

    public List<String> mTabs;//流式布局标签数据

    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        ScreenUtils.translateStatusBar((Activity) context);
        LayoutInflater.from(context).inflate(R.layout.search_layout, this);
        setStatusBar();
        initViews();
    }

    // 设置状态栏
    private void setStatusBar()
    {
        statusBar = findViewById(R.id.statu_bar);
        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
        layoutParams.height = ScreenUtils.getStatusHeight(mContext);
        statusBar.setLayoutParams(layoutParams);
    }

    private void initViews()
    {

        etInput = (EditText) findViewById(R.id.search_et_input);
        ivDelete = (ImageView) findViewById(R.id.search_iv_delete);
        btnBack= (ImageView) findViewById(R.id.search_btn_back);
        lvTips = (MyListView) findViewById(R.id.search_lv_tips);
        mFBLayout = (FlexboxLayout) findViewById(R.id.xl_search_tab);
        mRlTabStr = (RelativeLayout) findViewById(R.id.rl_tab_str);
        lvTips.setOverScrollMode(View.OVER_SCROLL_NEVER);

        lvTips.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //set edit text
                String text = lvTips.getAdapter().getItem(i).toString();
                etInput.setText(text);
                etInput.setSelection(text.length());
                //hint list view gone and result list view show
//                hitroyAndLine.setVisibility(View.GONE);
                notifyStartSearching(text);
            }
        });

        ivDelete.setOnClickListener(this);
        btnBack.setOnClickListener(this);

        etInput.addTextChangedListener(new EditChangedListener());
        etInput.setOnClickListener(this);
        etInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    hitroyAndLine.setVisibility(GONE);
                    notifyStartSearching(etInput.getText().toString());
                }
                return true;
            }
        });

//        mFBLayout.setOnItemClick(this);
    }

    /**
     * 通知监听者 进行搜索操作
     * @param text
     */
    private void notifyStartSearching(String text){
        if (mListener != null) {
            mListener.onSearch(etInput.getText().toString());
        }
        //隐藏软键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 设置热搜版提示 adapter
     */
    public void setHistoryAdapter(HistoryAdapter mHistoryAdapter) {
        this.mHistoryAdapter = mHistoryAdapter;
        if (lvTips.getAdapter() == null) {
            lvTips.setAdapter(mHistoryAdapter);
        }
    }

    /**
     * 设置自动补全adapter
     */
    public void setAutoCompleteAdapter(ArrayAdapter<String> adapter) {
        this.mAutoCompleteAdapter = adapter;
    }


   /* @Override
    public void onSingleClick(View view, int pos) {
        if(StringUtils.isNull(mTabs)||pos>=mTabs.size()){
            return;
        }
        String mTabObj=mTabs.get(pos);
        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_TAB_CALL,mTabObj));//点击的pos
    }*/

    private class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            if (!"".equals(charSequence.toString())) {
                ivDelete.setVisibility(VISIBLE);
//                hitroyAndLine.setVisibility(VISIBLE);
                if (mAutoCompleteAdapter != null && lvTips.getAdapter() != mAutoCompleteAdapter) {
                    lvTips.setAdapter(mAutoCompleteAdapter);
                }
            } else {
                ivDelete.setVisibility(GONE);
                if (mHistoryAdapter != null) {
                    lvTips.setAdapter(mHistoryAdapter);
                }
            }
            //更新autoComplete数据
            if (mListener != null) {
                mListener.onRefreshAutoComplete(charSequence + "");
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.search_et_input) {
//            hitroyAndLine.setVisibility(VISIBLE);

        } else if (i == R.id.search_iv_delete) {
            etInput.setText("");
            ivDelete.setVisibility(GONE);

        } else if (i == R.id.search_btn_back) {
            if(backmListener!=null){
                backmListener.onClick(view);
            }
        }
    }

    /**
     * search view回调方法
     */
    public interface SearchViewListener {

        /**
         * 更新自动补全内容
         *
         * @param text 传入补全后的文本
         */
        void onRefreshAutoComplete(String text);

        /**
         * 开始搜索
         *
         * @param text 传入输入框的文本
         */
        void onSearch(String text);
    }

    /**
     * 搜索框设置提示文本
     * @param strHint 提示文本
     */

    public void setSearchHint(String strHint){
        etInput.setHint(strHint);
    }
    /**
     * 设置搜索标签 Date
     */
    public void setSearchTabData(List<String> mTabs){
        this.mTabs=mTabs;
        if(StringUtils.isNull(mTabs)){
            mRlTabStr.setVisibility(GONE);
            mFBLayout.setVisibility(GONE);
            return;
        }else{
            mRlTabStr.setVisibility(VISIBLE);
            mFBLayout.setVisibility(VISIBLE);
        }
        mFBLayout.removeAllViews();
        for (int i=0;i<mTabs.size();i++) {
            String mTab=mTabs.get(i);
            mFBLayout.addView(createNewFlexItemTextView(mTab));
        }
    }
    public void setEtInput(String mKeyWord){
        etInput.setText(mKeyWord);
        etInput.requestFocus();
    }

    /**
     * 动态创建TextView
     * @return
     */
    private TextView createNewFlexItemTextView(final String mTab) {
        TextView mTabView = new TextView(mContext);
        mTabView.setGravity(Gravity.CENTER);
        mTabView.setText(mTab);
        mTabView.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimensionPixelSize(R.dimen.tab_content_size));
        mTabView.setTextColor(getResources().getColor(R.color.c_666666));
        mTabView.setBackgroundResource(R.drawable.sp_tab);
        int padding = SizeUtils.dp2px(mContext, 4);
        int paddingLeftAndRight = SizeUtils.dp2px(mContext, 8);
        ViewCompat.setPaddingRelative(mTabView, paddingLeftAndRight, padding, paddingLeftAndRight, padding);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mTabView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_TAB_CALL,mTab));//点击的pos
            }
        });
        int margin = SizeUtils.dp2px(mContext, 6);
        int marginTop = SizeUtils.dp2px(mContext, 16);
        layoutParams.setMargins(margin, marginTop, margin, 0);
        mTabView.setLayoutParams(layoutParams);
        return mTabView;
    }
}